package com.vm.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.vm.activity.ActiveActivity;
import com.vm.activity.BitmapCache;
import com.vm.adapter.CategoryAppGridAdapter;
import com.vm.commons.StringUtil;
import com.vm.commons.VMConst;
import com.vm.model.AppType;
import com.vm.utils.JsonUtils;
import com.vm.utils.MyVolley;
import com.wwt.app.R;

public class CategoryAppFragment extends BaseFragment {
	protected static final String TAG = null;
	private RequestQueue mQueue;
	private List<AppType> listapptypes;
	// private Button btn_small_category;
	LinearLayout llayout_list;
	private View view;
	/** 标志位，标志已经初始化完成 */
	private boolean isPrepared;
	/** 是否已被加载过一次，第二次就不再去请求数据了 */
	private boolean mHasLoadedOnce;

	TextView tv_top_recommended;
	TextView tv_topical_application;
	TextView tv_latest_application;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		Log.i("CategoryGameFragment", "onCreateView");

		if (view == null) {
			view = inflater.inflate(R.layout.category_apply_list, null);
		} else {
			// 缓存的rootView需要判断是否已经被加过parent
			// 如果有parent需要从parent删除
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null) {
				parent.removeView(view);
			}
		}
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Log.e(TAG, "App");

		isPrepared = true;
		lazyLoad();

	}

	public void initView() {
		tv_top_recommended = (TextView) view
				.findViewById(R.id.tv_top_recommended);
		tv_topical_application = (TextView) view
				.findViewById(R.id.tv_topical_application);
		tv_latest_application = (TextView) view
				.findViewById(R.id.tv_latest_application);

		tv_top_recommended.setOnClickListener(textClickListener);
		tv_topical_application.setOnClickListener(textClickListener);
		tv_latest_application.setOnClickListener(textClickListener);
	}

	OnClickListener textClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent;
			String activeType = null;
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.tv_top_recommended:
				intent = new Intent(getActivity(), ActiveActivity.class);
				activeType = VMConst.ActiveType.getTopRecommended.toString();
				intent.putExtra("activeType", activeType);
				intent.putExtra("currentType",
						VMConst.ActiveTypeName.精品推荐.toString());
				startActivityForResult(intent, 10);
				break;
			case R.id.tv_topical_application:
				intent = new Intent(getActivity(), ActiveActivity.class);
				intent.putExtra("activeType",
						VMConst.ActiveType.getHotApp.toString());
				intent.putExtra("currentType",
						VMConst.ActiveTypeName.热门应用.toString());
				startActivityForResult(intent, 10);
				break;
			case R.id.tv_latest_application:
				intent = new Intent(getActivity(), ActiveActivity.class);
				intent.putExtra("activeType",
						VMConst.ActiveType.getLatestApp.toString());
				intent.putExtra("currentType",
						VMConst.ActiveTypeName.最新应用.toString());
				startActivityForResult(intent, 10);
				break;

			default:
				break;
			}

		}
	};

	static class ViewHolder {
		TextView tv_big_category;
		GridView gridView1;
		List<AppType> gridtypes;
		ImageView iv_big_category;
	}

	@Override
	protected void lazyLoad() {
		// TODO Auto-generated method stub

		if (!isPrepared || !isVisible || mHasLoadedOnce) {
			return;
		}

		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// 显示加载进度对话框
				initView();
				UIHelper.showDialogForLoading(getActivity(), "正在加载...", true);
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try {
					Thread.sleep(300);
					initData();
					// 在这里添加调用接口获取数据的代码
					// doSomething()
				} catch (Exception e) {
					e.printStackTrace();
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean isSuccess) {
				if (isSuccess) {
					// 加载成功
					// setView();
					mHasLoadedOnce = true;
				} else {
					// 加载失败
				}
				// 关闭对话框
				UIHelper.hideDialogForLoading();
			}
		}.execute();

	}

	public void initData() {
		llayout_list = (LinearLayout) view.findViewById(R.id.llayout_list);
		mQueue = MyVolley.getRequestQueue();
		listapptypes = new ArrayList<AppType>();
		JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(
				"http://www.91pcapp.com/json/getAllAppType",
				new Listener<JSONArray>() {

					@Override
					public void onResponse(JSONArray arg0) {
						// TODO Auto-generated method stub
						for (int i = 0; i < arg0.length(); i++) {
							try {
								JSONObject jsonObject = arg0.getJSONObject(i);
								// String s=jsonObject.toString();

								AppType apptype = JsonUtils.jsonToBean(
										jsonObject, AppType.class);
								String s = apptype.toString();
								Log.i(TAG, s);

								// 动态添加
								ViewHolder viewHolder = null;

								View convertView = LayoutInflater.from(
										getActivity()).inflate(
										R.layout.category_apply_item, null);
								viewHolder = new ViewHolder();

								viewHolder.tv_big_category = (TextView) convertView
										.findViewById(R.id.tv_big_category);
								viewHolder.gridView1 = (GridView) convertView
										.findViewById(R.id.gridView1);
								viewHolder.iv_big_category = (ImageView) convertView
										.findViewById(R.id.iv_big_category);

								convertView.setTag(viewHolder);

								viewHolder.tv_big_category.setTag(apptype
										.getId());
								viewHolder.tv_big_category.setText(StringUtil
										.getShotName(apptype.getName()));

								// for(int
								// i=0;i<apptype.getChildTypes().size();i++){
								// gridtype.add(apptype);
								// }
								List<AppType> gridtype = new ArrayList<AppType>();
								gridtype = apptype.getChildTypes();

								CategoryAppGridAdapter myAdapter = new CategoryAppGridAdapter(
										getActivity(), gridtype);
								viewHolder.gridView1.setAdapter(myAdapter);

								ImageLoader mImageLoader = new ImageLoader(
										mQueue, new BitmapCache());
								ImageListener listener = ImageLoader
										.getImageListener(
												viewHolder.iv_big_category,
												R.drawable.apply_feature,
												R.drawable.apply_feature);

								mImageLoader.get(
										VMConst.URL + apptype.getImageUrl(),
										listener);

								llayout_list.addView(convertView);

							} catch (JSONException e) {
								e.printStackTrace();
							}
						}

					}

				}, new Response.ErrorListener() {
					public void onErrorResponse(VolleyError error) {
						Log.e(TAG, error.getMessage(), error);
					}
				});
		mQueue.add(jsonObjectRequest);
	}

}
